/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 20:21:05
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-25 22:27:14
 * @FilePath: \vue3_nuxt_demo\server\api\notebook\notebook.post.ts
 * @Description: 创建文集接口
 */
import Joi from 'joi';
import { responseJson, getLoginUid } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/***
 * 创建文集
 */

export default defineEventHandler(
  async (event) => {

    //获取用户id，判断是否登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401, {
        success: false,
        msg: '请先登录',
        data: []
      });
    }

    // 获取请求体
    const body = await readBody(event);
    // 数据校验
    const schema = Joi.object({
        name: Joi.string().required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(body);
    }
    catch (error) {
      return responseJson(400, {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      // 请求体
      const { name } = body;
      //创建文集
      const [rows] = await con.execute(
        'insert into `notebooks` (`name`,`uid`) value (?,?)',
        [name, uid]
      );

      if (rows.affectedRows === 0) {
          return responseJson(400,{
            success: false,
            msg: '创建失败',
            data: []
          });
      }
      return responseJson(200,{
        success: true,
        msg: '创建成功'
      });

    }
    catch (error){
      // 设置响应状态码
      setResponseStatus(event,500);
      // 响应
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
  }
);